<?php
/**
 * 5.9版本每月1号增加一条过期明细
 * @author wangzhenxing
 */

ini_set('memory_limit', -1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Doraemon\model\PointMonth as mPointMonth;
use Doraemon\model\Points;
use Doraemon\tools\PointConfig;
use Doraemon\tools\Log;

$t1 = microtime(true);
$month = date('Ym', strtotime('-12 month'));
$tableNum = mPointMonth::_SUB_TABLE_NUM;

for ($i = 0; $i < $tableNum; $i++) {
    $tabStar = microtime(true);
    $pageSize = 10000;
    $page = 1;
    $list = [];
    $userNum = 0;
    do {
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where = [
            'AND' => [
                'month' => $month,
                'remain_point[>]' => 0
            ],
            'LIMIT' => $limit
        ];
        $tstart = microtime(true);
        mPointMonth::enforceSubTableNameSuffix($i);
        $list = mPointMonth::select(['uid', 'remain_point'], $where);
        mPointMonth::resetEnforceSubTable();
        if ($list) {
            addExpireDetail($list, $month);
        }
        $tend = microtime(true);
        $ttime = $tend - $tstart;

        $userNum = $userNum + count($list);
        $page++;
    } while ($list);
    $tabEnd = microtime(true);
    $time = $tabEnd - $tabStar;
    Log::debug($i . '表执行完毕', ['量' => $userNum, '时' => number_format($time, 2) . 's']);
}
$t2 = microtime(true);
$time = $t2 - $t1;
$mtime = ($time * 1000) . 'ms';
Log::debug('表全部执行完毕', ['时' => number_format($time, 2) . 's ']);

function addExpireDetail($list, $month)
{
    foreach ($list as $row) {
        $uid = $row['uid'];
        $point = $row['remain_point'];
        $request_id = md5(microtime() . $row['uid'] . mt_rand(0, 100000) . Points::TYPE_DEDUCT);

        $pointData = [
            'uid' => $uid,
            'type' => Points::TYPE_DEDUCT,
            'hope_point' => $point,
            'real_point' => $point,
            'event_name' => PointConfig::POINT_TYPE_NATURE_EXPIRE,
            'request_id' => $request_id,
            'source' => 'admin',
            'ext_info' => json_encode(['detail' => $month . '积分自然过期']),
            'addtime' => time()
        ];
        try {
            $res = Points::addInfo($pointData);
            if (empty($res)) {
                Log::debug('失败：积分明细插入失败', ['res' => $res, 'data' => $pointData]);
            }
        } catch (Exception $e) {
            Log::debug('错误：积分明细插入出错',
                [
                    'error' => $e->getMessage() . $e->getFile() . $e->getLine(),
                    'data' => $pointData
                ]);
        }
    }
}